<template>
  <div>
    <div id="components-form-demo-advanced-search">
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          客户编号：
          <a-select
            show-search
            option-filter-prop="children"
            style="width: 60%"
            :filter-option="filterOption"
            v-model="searchData.tenantId"
          >
            <a-select-option
              :value="item.tenantId"
              v-for="item in accArray"
              :key="item.id"
              :titles="item.title"
            >
              {{ item.companyName + "/" + item.tenantId }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          货物编号：<a-input
            :maxLength="128"
            style="width: 60%"
            v-model="searchData.goodsBoxNo"
          />
        </a-col>
        <a-col :span="6">
          SKU：<a-input
            :maxLength="128"
            style="width: 60%"
            v-model="searchData.skus"
          />
        </a-col>
        <a-col :span="6" v-show="expand">
          仓库：
          <a-select
            show-search
            option-filter-prop="children"
            style="width: 60%"
            :filter-option="filterOption"
            v-model="searchData.warehouseId"
            allowClear
            placeholder="全部"
          >
            <a-select-option
              :value="item.warehouseId"
              v-for="item in warehouse"
              :key="item.warehouseId"
            >
              {{ item.titleName }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <div v-show="!expand">
            <a-button
              type="primary"
              class="searchBtn"
              @click="
                () => {
                  searchDataBtn();
                }
              "
            >
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="resetSearch"
            >
              重置
            </a-button>
            <a
              :style="{ marginRight: '8px', fontSize: '14px' }"
              @click="expand = !expand"
            >
              {{ expand ? "折叠" : "展开" }}
              <a-icon :type="expand ? 'up' : 'down'" />
            </a>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          <div v-show="expand">
            <a-button
              type="primary"
              class="searchBtn"
              @click="
                () => {
                  searchDataBtn();
                }
              "
            >
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="resetSearch"
            >
              重置
            </a-button>
            <a
              :style="{ marginRight: '8px', fontSize: '14px' }"
              @click="expand = !expand"
            >
              {{ expand ? "折叠" : "展开" }}
              <a-icon :type="expand ? 'up' : 'down'" />
            </a>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-spin tip="Loading..." :spinning="spinning">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :scroll="{ x: 1500 }"
      >
        <span slot="productTag" slot-scope="text, record">
          {{
            record.relevancySku === null
              ? record.productTag
              : record.productTag + "/" + record.relevancySku
          }}
        </span>
        <span slot="skus" slot-scope="text, record">
          <div v-for="(item, index) in record.skus" :key="index">
            <div>{{ item }}<br /></div>
          </div>
        </span>
        <span slot="action" slot-scope="text, record">
          <a
            href="javascript:;"
            style="text-decoration: underline; color: rgb(41, 41, 224)"
            @click="freightSpaceInfo(record)"
            >仓位明细
          </a>
          <a-divider type="vertical" />
          <a
            href="javascript:;"
            style="text-decoration: underline; color: rgb(41, 41, 224)"
            @click="outPutInStorage(record)"
            >出入库记录
          </a>
        </span>
      </a-table>
    </a-spin>
    <!-- 分页器 -->
    <div style="margin: 20px 0; text-align: center">
      <a-config-provider>
        <a-pagination
          :current="searchData.current"
          show-size-changer
          :pageSizeOptions="['10', '20', '30']"
          :show-total="
            (total) => `${$t('m.page.Total')} ${total} ${$t('m.page.items')}`
          "
          @showSizeChange="showChange"
          :buildOptionText="
            (props) => ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
          "
          show-quick-jumper
          :default-current="searchData.current"
          :total="total"
          @change="onChangePage"
        />
      </a-config-provider>
    </div>
    <!-- //仓位明细模态框 -->
    <a-modal v-model="freightSpaceVisible" width="836px" title="仓位明细">
      <template slot="footer">
        <a-button
          style="background: #d7d7d7; color: #fff; border: none"
          @click="
            () => {
              this.freightSpaceVisible = false;
            }
          "
          >取消</a-button
        >
        <!-- <a-button :loading="loading" type="primary" @click="freightSpaceSave"
          >保存</a-button
        > -->
      </template>
      <p>
        货物编号：{{
          freightSpace.records ? freightSpace.records[0].goodsBoxNo : ""
        }}
      </p>
      <a-spin tip="Loading..." :spinning="spinning">
        <a-table
          size="small"
          :columns="freightSpaceColumns"
          :data-source="freightSpace.records"
          :pagination="false"
        >
          <span slot="warehousingNames" slot-scope="text, record">
            {{
              record.warehousingNames == null
                ? "未选择仓位"
                : record.warehousingNames.replaceAll(",", "-")
            }}
          </span>
        </a-table>
      </a-spin>
    </a-modal>

    <!-- 出入库记录 -->
    <a-modal
      v-model="outPutInStorageVisible"
      @cancel="cancelModal"
      width="80%"
      title="出入库记录"
    >
      <template slot="footer">
        <a-button
          style="background: #d7d7d7; color: #fff; border: none"
          @click="cancelModal"
          >关闭</a-button
        >
      </template>
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          业务类型：
          <a-select
            size="small"
            defaultValue="-1"
            style="width: 60%"
            v-model="outPutInStorageSarchData.businessType"
          >
            <a-select-option value="-1"> 全部 </a-select-option>
            <a-select-option value="0"> 转运入库 </a-select-option>
            <!-- <a-select-option value="1"> </a-select-option> -->
            <a-select-option value="2"> 转运出库锁定 </a-select-option>
            <a-select-option value="3"> 转出锁定退回 </a-select-option>
            <a-select-option value="4"> 转运实际出库</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          仓位：
          <a-cascader
            style="width: 60%"
            size="small"
            change-on-select
            :options="storageLocation"
            v-model="storageLocationValue"
            @change="onChangeOutPutInStorage"
            placeholder="请选择库位"
          />
        </a-col>
        <a-col :span="6">
          日期：
          <a-range-picker
            size="small"
            style="width: 60%"
            v-model="modalDate"
            @change="onChangeModalDate"
          />
        </a-col>
        <a-col :span="6">
          <div>
            <a-button
              size="small"
              type="primary"
              class="searchBtn"
              @click="
                () => {
                  outPutInStorage(currentRowObj);
                }
              "
            >
              查询
            </a-button>
            <a-button
              size="small"
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="outPutInStorageReset"
            >
              重置
            </a-button>
            <!-- <a-button
              size="small"
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
            >
              导出
            </a-button> -->
          </div>
        </a-col>
      </a-row>
      <a-table
        size="small"
        :columns="outPutInStorageColumns"
        :data-source="outPutInStorageData"
        :pagination="false"
      >
        <span slot="warehousingNames" slot-scope="text, record">
          {{
            record.warehousingNames == null
              ? "未选择仓位"
              : record.warehousingNames.replaceAll(",", "-")
          }}
        </span>
        <span slot="createdTime" slot-scope="text, record">
          {{ record.createdTime.replaceAll("T", "  ") }}
        </span>
      </a-table>
      <!-- 分页器 -->
      <div style="margin: 20px 0; text-align: center">
        <a-config-provider>
          <a-pagination
            show-size-changer
            :pageSizeOptions="['10', '20', '30']"
            :show-total="
              (total) =>
                `${$t('m.page.Total')} ${modalTotal} ${$t('m.page.items')}`
            "
            @showSizeChange="outPutInStorageShowChange"
            :buildOptionText="
              (props) =>
                ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
            "
            show-quick-jumper
            :current="outPutInStorageSarchData.current"
            :total="modalTotal"
            @change="outPutInStorageChangePage"
          />
        </a-config-provider>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  bybehalf_stock,
  bybehalf_listpid,
  searchList,
} from "@/apis/system/StockManagement/inventory";
import { warehouse, warehouse_select } from "@/apis/common";
export default {
  created() {
    this.getTabDataList();
    this.getwWrehouseList();
  },
  data() {
    return {
      spinning: false,
      modalDate: null,
      storageLocationValue: [],
      // 出入库记录数据
      outPutInStorageData: [],
      loading: false,
      //库位数据
      storageLocation: [],
      // 仓位明细列表
      freightSpace: {},
      //   仓位明细模态框
      freightSpaceVisible: false,
      //   出入库记录模态框
      outPutInStorageVisible: false,
      //   表格数据
      tableData: [],
      // 分页总条数
      total: 0,
      //仓库
      warehouse: [],
      expand: false,
      //   页面搜索
      searchData: {
        current: 1,
        size: 10,
        skus: null,
        goodsBoxNo: null,
        tenantId: null,
        warehouseId: null,
      },
      //   表格出入库模态框搜索
      outPutInStorageSarchData: {
        current: 1,
        endTime: null,
        startTime: null,
        warehouseId: null,
        transferNo: null,
        size: 10,
        transferWarehousingBoxId: null,
        tenantId: null,
        warehousingId: null,
        skus: null,
        businessType: "-1",
      },
      modalTotal: 0,
      //每一行数据
      currentRowObj: {},
    };
  },
  methods: {
    //取消模态框事件
    cancelModal() {
      this.outPutInStorageSarchData.current = 1;
      this.outPutInStorageVisible = false;
    },
    //出入库记录
    async outPutInStorage(record) {
      this.spinning = true;
      this.currentRowObj = record;
      this.outPutInStorageSarchData.warehouseId = record.warehouseId;
      this.outPutInStorageSarchData.transferNo = record.transferNo;
      this.outPutInStorageSarchData.tenantId = record.tenantId;
      this.outPutInStorageSarchData.transferWarehousingBoxId =
        record.transferWarehousingBoxId;
      if (!this.outPutInStorageVisible) {
        this.getStorageLocation(record.warehouseId);
      }
      this.outPutInStorageVisible = true;
      let { code, responseBody } = await searchList(
        record.transferWarehousingApplyId,
        record.transferWarehousingBoxId,
        this.outPutInStorageSarchData.businessType,
        this.outPutInStorageSarchData
      );
      if (code === "200") {
        responseBody.records.forEach((item) => {
          if (item.businessType == "0") {
            item.businessType = "转运入库";
          } else if (item.businessType == "2") {
            item.businessType = "转运出库锁定";
          } else if (item.businessType == "3") {
            item.businessType = "转出锁定退回";
          } else if (item.businessType == "4") {
            item.businessType = "转运实际出库";
          }
        });
        this.outPutInStorageData = responseBody.records;
        this.modalTotal = responseBody.total * 1;
        this.spinning = false;
      }
    },
    //出入库查询按钮
    searchDataBtn() {
      this.searchData.current = 1;
      this.getTabDataList();
    },
    //出入库记录重置按钮
    outPutInStorageReset() {
      this.outPutInStorageSarchData.startTime = null;
      this.outPutInStorageSarchData.endTime = null;
      this.outPutInStorageSarchData.current = 1;
      this.outPutInStorageSarchData.size = 10;
      this.outPutInStorageSarchData.warehousingIds = null;
      this.outPutInStorageSarchData.warehousingId = null;
      this.outPutInStorageSarchData.businessType = "-1";
      this.modalDate = null;
      this.storageLocationValue = [];
      this.outPutInStorage(this.currentRowObj);
    },
    // //仓位明细模态框保存
    // freightSpaceSave() {
    //   this.loading = true;
    //   setTimeout(async () => {
    //     let { code } = await bybehalf_upDateStock(this.freightSpace.listPr);
    //     if (code === "10000") {
    //       this.getTabDataList();
    //       this.loading = false;
    //       this.freightSpaceVisible = false;
    //     }
    //   }, 1000);
    // },
    //重置按钮
    resetSearch() {
      let current = this.searchData.current;
      let size = this.searchData.size;
      for (let key in this.searchData) {
        this.searchData[key] = null;
      }

      this.searchData.size = size;
      this.searchData.current = current;
      this.getTabDataList();
    },
    //获取仓库
    async getwWrehouseList() {
      let { code, responseBody } = await warehouse({
        warehousePid: 0,
      });
      if (code === "200") {
        this.warehouse = [...responseBody];
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //分页器事件
    onChangePage(pageNumber) {
      this.searchData.current = pageNumber;
      this.getTabDataList();
    },
    //页码变更
    showChange(size, current) {
      this.searchData.current = size;
      this.searchData.size = current;
      this.getTabDataList();
    },
    //分页器事件
    outPutInStorageChangePage(pageNumber) {
      this.outPutInStorageSarchData.current = pageNumber;
      this.outPutInStorage(this.currentRowObj);
    },
    //页码变更
    outPutInStorageShowChange(size, current) {
      this.outPutInStorageSarchData.current = size;
      this.outPutInStorageSarchData.size = current;
      this.outPutInStorage(this.currentRowObj);
    },
    //表格数据
    async getTabDataList() {
      this.spinning = true;
      if (this.searchData.warehousingId == "全部") {
        this.searchData.warehousingId = null;
      }
      let { code, responseBody } = await bybehalf_stock(this.searchData);
      if (code === "200") {
        responseBody.records.forEach((item) => {
          item.key = item.id;
        });
        this.tableData = responseBody.records;
        this.total = responseBody.total * 1;
        this.tableData.forEach((item) => {
          if (item.skus) {
            item.skus = item.skus.split(",");
          }
        });
        this.spinning = false;
      }
    },
    // 每一行仓位明细
    async freightSpaceInfo(record) {
      let params = {
        warehouseId: record.warehouseId,
        goodsBoxNo: record.goodsBoxNo || null,
        skus: record.skus.join(","),
        transferWarehousingApplyId: record.transferWarehousingApplyId,
        transferWarehousingBoxId: record.transferWarehousingBoxId,
      };
      let { code, responseBody } = await bybehalf_listpid(params);
      if (code === "200") {
        this.freightSpace = responseBody;
      }
      this.getStorageLocation(record.warehousingId);
      this.freightSpaceVisible = true;
    },
    async getStorageLocation(id) {
      let { code, responseBody } = await warehouse_select({
        warehousePid: id,
        isTree: true,
      });
      if (code === "200") {
        this.storageLocation = this.getSkuTypeThree(responseBody);
      }
    },
    //封装组装后台数据
    getSkuTypeThree(data) {
      data.forEach((item) => {
        item.label = item.titleName;
        item.children = item.child;
        item.value = item.warehouseId;
        item.sort = this.sort;
        if (item.children && item.children.length >= 1) {
          this.sort += 1;
          this.getSkuTypeThree(item.children);
        }
      });
      this.sort = 0;
      return data;
    },
    // 改变库位
    onChangeLocation(value, selectedOptions, item) {
      item.newLocationId = value.join(",");
      let arr = [];
      selectedOptions.forEach((item) => {
        arr.push(item.titleName);
        item.newLocationName += item.titleName;
      });
      item.newLocationName = arr.join(",");
    },
    //模态框搜索库位改变
    onChangeOutPutInStorage(value, options) {
      if (options) {
        this.outPutInStorageSarchData.warehousingIds = value.join(",");
        this.outPutInStorageSarchData.warehousingId =
          options[options.length - 1].value;
      } else {
        this.outPutInStorageSarchData.warehousingIds = undefined;
        this.outPutInStorageSarchData.warehousingId = null;
      }
    },
    // 模态框时间改变
    onChangeModalDate(date, dateString) {
      this.outPutInStorageSarchData.startTime = `${dateString[0]} 00:00:00`;
      this.outPutInStorageSarchData.endTime = `${dateString[1]} 23:59:59`;
    },
  },
  computed: {
    ...mapState(["accArray"]),
    columns() {
      return [
        {
          title: "客户编号",
          dataIndex: "tenantId",
          align: "center",
          scopedSlots: { customRender: "tenantId" },
          width: "14%",
        },
        {
          title: "入库仓库",
          dataIndex: "warehouseName",
          align: "center",
          scopedSlots: { customRender: "warehouseName" },
          width: "10%",
        },
        {
          title: "入库代码",
          dataIndex: "transferNo",
          align: "center",
          scopedSlots: { customRender: "transferNo" },
          width: "14%",
        },
        {
          title: "货物编号",
          dataIndex: "goodsBoxNo",
          align: "center",
          scopedSlots: { customRender: "goodsBoxNo" },
          width: "14%",
        },
        {
          title: "SKU",
          dataIndex: "skus",
          align: "center",
          scopedSlots: { customRender: "skus" },
          width: "14%",
        },
        {
          title: "在库数量（箱）",
          dataIndex: "total",
          align: "center",
          scopedSlots: { customRender: "total" },
          width: "14%",
        },
        {
          title: "等待入库",
          dataIndex: "waitLockingTotal",
          align: "center",
          scopedSlots: { customRender: "waitLockingTotal" },
          width: "14%",
        },
        {
          title: "等待出库",
          dataIndex: "outLockingTotal",
          align: "center",
          scopedSlots: { customRender: "outLockingTotal" },
          width: "14%",
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: "15%",
        },
      ];
    },
    freightSpaceColumns() {
      return [
        {
          title: "仓位",
          dataIndex: "warehousingNames",
          align: "center",
          scopedSlots: { customRender: "warehousingNames" },
          width: "25%",
        },
        {
          title: "在库数量（箱）",
          dataIndex: "total",
          align: "center",
          scopedSlots: { customRender: "total" },
          width: "25%",
        },
        {
          title: "待出库库存",
          dataIndex: "outLockingTotal",
          align: "center",
          scopedSlots: { customRender: "outLockingTotal" },
          width: "25%",
        },
        {
          title: "等待入库库存",
          dataIndex: "waitLockingTotal",
          align: "center",
          scopedSlots: { customRender: "waitLockingTotal" },
          width: "25%",
        },
      ];
    },
    outPutInStorageColumns() {
      return [
        {
          title: "业务类型",
          dataIndex: "businessType",
          align: "center",
          scopedSlots: { customRender: "businessType" },
          width: "14%",
        },

        {
          title: "货物编号",
          dataIndex: "goodsBoxNo",
          align: "center",
          scopedSlots: { customRender: "goodsBoxNo" },
          width: "16%",
        },
        {
          title: "仓位",
          dataIndex: "warehousingNames",
          align: "center",
          scopedSlots: { customRender: "warehousingNames" },
          width: "14%",
        },
        {
          title: "箱数",
          dataIndex: "thisReceive",
          align: "center",
          scopedSlots: { customRender: "thisReceive" },
          width: "14%",
        },

        {
          title: "操作时间",
          dataIndex: "createdTime",
          align: "center",
          scopedSlots: { customRender: "createdTime" },
          width: "14%",
        },
        {
          title: "操作账号",
          dataIndex: "createdName",
          align: "center",
          scopedSlots: { customRender: "createdName" },
          width: "14%",
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
.searchBtn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.searchBtn:hover {
  background: #3eae7c;
  color: #fff;
}
</style>
